package app.serialport;

import java.io.IOException;
import java.util.TooManyListenersException;
import java.util.concurrent.atomic.AtomicInteger;

import app.serialport.LongValue;

public class SerialPortTest {

	public static void main(String[] args) throws IOException, TooManyListenersException, InterruptedException {
		for (String s : SerialPort.getAvailableSerialPorts()) {
			System.out.println("Availible port: " + s);
		}
//		String port = "COM5";//"/dev/tty.SLAB_USBtoUART";
//		int baudRate = 115200;
		
		SerialPortConfig serialPortConfig = new SerialPortConfig();
		serialPortConfig.setPort("COM3");
		serialPortConfig.setBaudRate(115200);
		serialPortConfig.setTimeOut(5*1000);
		
		final SerialPort hardwareSerialPort = new SerialPort(serialPortConfig);
		hardwareSerialPort.connect();
		hardwareSerialPort.setDefaultDecoder(new DelimiterDecoder("8B 8B"));
		
		final AtomicInteger atomicInteger = new AtomicInteger();
		final LongValue allCost = new LongValue(0);
		hardwareSerialPort.addListener(new DataRecivedListener() {
			@Override
			public void onRecived(byte[] data, long cost) {
				allCost.add(cost);
				atomicInteger.getAndIncrement();
				
//				if(atomicInteger.get()%10==0) {
////					System.out.println(allCost.get());
////					System.out.println(atomicInteger.get());
//					long avgCost = allCost.get()/(atomicInteger.get()+0L);
////					System.out.println(atomicInteger.get()%10==0);
////					System.out.println(avgCost);
////					System.out.println("cost:" + allCost.get()/atomicInteger.get());
//					System.out.println("recived["+atomicInteger.get()+"], avgCost: "+avgCost);	
//				}
				
//				System.out.println("recived["+atomicInteger.get()+"], cost: "+cost+",message:" + ByteUtil.bytes2HexString(data));	
				//hardwareSerialPort.disconnect();
			}
		});
		
		Thread.sleep(1000);
		
//		System.out.println("read boards");
		String data = "7E 00 7E A6";
		byte[] responseData = hardwareSerialPort.sendDataAwait(data);
//		System.out.println("boards:" + ByteUtil.bytes2HexString(responseData));
		for (int i = 0; i < 0; i++) {
			data = "7E 00 7E A2";
//			if(i==3) {
//				data = "07 05 00 01 FF 00 dd 9c";
//			} 
//			if(i==4) {
//				data = "07 05 00 01 FF 00 dd 9c";
//			} 
//			if(i==5) {
//				data = "07 05 00 01 FF 00 dd 9c";
//			} 
//			System.out.println(data);
//			data = "06 05 00 01 FF 00 dc 4d";
//			System.out.println("read boards info");
			responseData = hardwareSerialPort.sendDataAwait(data);
//			System.out.println("boards info:" + ByteUtil.bytes2HexString(responseData));
		}
		
		 data = "7E 00 7E A3";
//		 responseData = hardwareSerialPort.sendDataAwait(data);
//		System.out.println("boards 2:" + ByteUtil.bytes2HexString(responseData));
		
//		Thread.sleep(10* 1000);
//		
//		hardwareSerialPort.disconnect();
	}
	
}
